package com.hippo.core.service;

import com.alibaba.fastjson.JSONObject;
import com.hippo.core.dao.FileManageDa0;
import com.hippo.core.util.CommonUtil;
import com.hippo.core.util.ExcelUtil;
import com.hippo.core.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: hippo
 */
@Slf4j
@Service
public class FileManageService {

    @Autowired
    private FileManageDa0 fileManageDa0;

    @Autowired
    private QiniuUtils qiniuUtils;

    public JSONObject upload(MultipartFile file) {
        String imagePath = qiniuUtils.upload(file);
        return CommonUtil.successJson(imagePath);
    }

    public JSONObject uploadCheck(MultipartFile file, String fieldName) {
        String imagePath = qiniuUtils.upload(file);
        try {
            ArrayList<String> fieldList = ExcelUtil.getFieldList(imagePath);
            if (!fieldList.contains(fieldName)) {
                return CommonUtil.errorJson("生成字段必须和文件首行有对应相同的名称");
            }
            List<Map<String, String>> maps = ExcelUtil.redExcel(imagePath);
            if (maps.size() == 0) {
                return CommonUtil.errorJson("关联的文件不能为空");
            }
        } catch (Exception e) {
            log.error(e.toString());
            return CommonUtil.errorJson(e.getMessage());
        }
        return CommonUtil.successJson(imagePath);
    }

    public JSONObject getFileManageList(JSONObject jsonObject) {
        CommonUtil.fillPageParam(jsonObject);
        int count = fileManageDa0.countFileManage(jsonObject);
        List<JSONObject> list = fileManageDa0.getFileManageList(jsonObject);
        return CommonUtil.successPage(jsonObject, list, count);
    }

    public JSONObject addFile(JSONObject data) {
        return CommonUtil.response(fileManageDa0.addFile(data));
    }

    public JSONObject deleteFile(String id) {
        return CommonUtil.response(fileManageDa0.deleteFile(id));
    }


}
